package com.woniuxy.woniufp.common.model;

import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import cn.hutool.jwt.signers.JWTSigner;
import cn.hutool.jwt.signers.JWTSignerUtil;
import org.springframework.core.io.ClassPathResource;
import org.springframework.security.rsa.crypto.KeyStoreKeyFactory;

import java.security.KeyPair;
import java.util.HashMap;
import java.util.Map;

public class TestJwt {
    public static void main(String[] args) {
        // 构建token中存储的数据，用map存储
        Map<String,Object> playload = new HashMap<>();
        playload.put("userId",100);
        playload.put("userName","jack");
        // 创建密钥对对象
        KeyStoreKeyFactory factory = new KeyStoreKeyFactory(
                new ClassPathResource("woniufp.jks"),"123456".toCharArray());
        KeyPair keyPair = factory.getKeyPair("woniufp");
        // 创建签名器
        JWTSigner jwtSigner = JWTSignerUtil.createSigner("RSA", keyPair);
        //【生成token】
        String token = JWTUtil.createToken(playload, jwtSigner);
        System.out.println("token = " + token);
        //【验证token】
        boolean verify = JWTUtil.verify(token, jwtSigner);
        System.out.println("verify = " + verify);
        //【解析token】
        if (verify) {
            JWT jwt = JWTUtil.parseToken(token);
            Object userId = jwt.getPayload("userId");
            System.out.println("userId = " + userId);
            Object userName = jwt.getPayload("userName");
            System.out.println("userName = " +userName);
        }
    }
}
